package com.lxd.common;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lxd.entity.ChatMsg;
import com.lxd.util.ProtostuffUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.HashMap;
import java.util.Map;

public class ServerHandler extends ChannelInboundHandlerAdapter {
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static Map<String,ChannelId> listUser=new HashMap<>();

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception{
        channels.add(ctx.channel());//加入ChannelGroup
        System.out.println(ctx.channel().id()+" 上线了"+"，目前在线人数: "+channels.size());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext context){
        System.out.println(context.channel().id()+" 下线"+"，目前在线人数: "+channels.size());
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        try {
            System.out.println(JSONObject.toJSONString(msg));
            //打印消息然后群发
            ChatMsg chatMsg= JSON.parseObject(msg.toString(),ChatMsg.class);
            if(0==chatMsg.getMsgType()){
                System.out.println("开始登录："+chatMsg.getName());
                if(chatMsg.getName().indexOf("test")==-1){
                    //非法登录 发送403报文退登
                    ChatMsg loginOut= ChatMsg.builder().code(403).msgType(0).build();
                    ctx.channel().writeAndFlush(JSONObject.toJSONString(loginOut));
                    ctx.channel().close();
                }else{
                    listUser.put(chatMsg.getName(),ctx.channel().id());
                }
                return;
            }else if(1==chatMsg.getMsgType()){//单聊消息
                ChannelId channelId=listUser.get(chatMsg.getToName());
                if(channelId==null){//存入离线消息
                    System.out.println("存入离线消息");
                }else{
                    //寻找消息接收人发送消息
                    for (Channel channel : channels) {
                        if(channelId==channel.id()){
                            channel.writeAndFlush(msg);
                        }
                    }
                }
            }else {//群聊消息
                for (Channel channel : channels) {
                    channel.writeAndFlush(msg.toString());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println(ctx.channel().id()+" 发生异常"+"，目前在线人数: "+channels.size());
        ctx.close();
    }
}
